<!doctype html>



  


<html class="theme-next pisces use-motion">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />












  
  
  <link href="/vendors/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/vendors/font-awesome/css/font-awesome.min.css?v=4.4.0" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.0.1" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="Java,Kafka,Redis,SpringBoot," />





  <link rel="alternate" href="/atom.xml" title="crossoverJie's Blog" type="application/atom+xml" />




  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.0.1" />






<meta name="description" content="前言之前在 Java-Interview 中提到过秒杀架构的设计，这次基于其中的理论简单实现了一下。

本次采用循序渐进的方式逐步提高性能达到并发秒杀的效果，文章较长请准备好瓜子板凳(liushuizhang😂)。

本文所有涉及的代码：

https://github.com/crossoverJie/SSM
https://github.com/crossoverJie/distribut">
<meta property="og:type" content="article">
<meta property="og:title" content="SSM(十八) 秒杀架构实践">
<meta property="og:url" content="http://crossoverjie.top/2018/05/07/ssm/SSM18-seconds-kill/index.html">
<meta property="og:site_name" content="crossoverJie's Blog">
<meta property="og:description" content="前言之前在 Java-Interview 中提到过秒杀架构的设计，这次基于其中的理论简单实现了一下。

本次采用循序渐进的方式逐步提高性能达到并发秒杀的效果，文章较长请准备好瓜子板凳(liushuizhang😂)。

本文所有涉及的代码：

https://github.com/crossoverJie/SSM
https://github.com/crossoverJie/distribut">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1d713e19ed.jpg">
<meta property="og:image" content="https://i.loli.net/2018/05/08/5af079ea8618b.png">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1d71693bb0.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1d7189c72f.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1d721e9fd4.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1d7243c657.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1d726cee79.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1d72816d67.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1d72b9f26a.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1d72dab853.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1d730800b1.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1d73324dd2.jpg">
<meta property="og:image" content="https://i.loli.net//2019//05//08//5cd1daafb70bc.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1d752909b9.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1d758c7714.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1d764221b5.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1d7676e1d2.jpg">
<meta property="og:image" content="https://i.loli.net//2019//05//08//5cd1daeb0c306.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1d776c39b7.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1d77ba16d2.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1d780d5aa2.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1d784644d5.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1d787b3e49.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1d78b3896a.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1d78d659b6.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1d790607a1.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1d79307676.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1d7973de43.jpg">
<meta property="og:updated_time" content="2019-05-07T19:23:27.306Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="SSM(十八) 秒杀架构实践">
<meta name="twitter:description" content="前言之前在 Java-Interview 中提到过秒杀架构的设计，这次基于其中的理论简单实现了一下。

本次采用循序渐进的方式逐步提高性能达到并发秒杀的效果，文章较长请准备好瓜子板凳(liushuizhang😂)。

本文所有涉及的代码：

https://github.com/crossoverJie/SSM
https://github.com/crossoverJie/distribut">
<meta name="twitter:image" content="https://i.loli.net/2019/05/08/5cd1d713e19ed.jpg">



<script type="text/javascript" id="hexo.configuration">
  var NexT = window.NexT || {};
  var CONFIG = {
    scheme: 'Pisces',
    sidebar: {"position":"left","display":"post"},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: 555390,
      author: 'crossoverJie'
    }
  };
</script>




  <link rel="canonical" href="http://crossoverjie.top/2018/05/07/ssm/SSM18-seconds-kill/"/>

  <title> SSM(十八) 秒杀架构实践 | crossoverJie's Blog </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="en">

  








  <div style="display: none;">
    <script src="https://s6.cnzz.com/stat.php?id=1259025147&web_id=1259025147" type="text/javascript"></script>
  </div>





  
  
    
  

  <div class="container one-collumn sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-meta ">
  

  <div class="custom-logo-site-title">
    <a href="/"  class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <span class="site-title">crossoverJie's Blog</span>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>
  <p class="site-subtitle">baller</p>
</div>

<div class="site-nav-toggle">
  <button>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
  </button>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            Home
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            Categories
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            About
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            Archives
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            Tags
          </a>
        </li>
      
        
        <li class="menu-item menu-item-photo">
          <a href="/favourite" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-photo"></i> <br />
            
            photo
          </a>
        </li>
      
        
        <li class="menu-item menu-item-jcsprout">
          <a href="https://crossoverjie.top/JCSprout/#/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-leaf"></i> <br />
            
            JCSprout
          </a>
        </li>
      
        
        <li class="menu-item menu-item-cicada">
          <a href="https://github.com/TogetherOS/cicada" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-github"></i> <br />
            
            cicada
          </a>
        </li>
      
        
        <li class="menu-item menu-item-cim">
          <a href="https://github.com/crossoverjie/cim" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-far fa-comment"></i> <br />
            
            CIM
          </a>
        </li>
      
        
        <li class="menu-item menu-item-vlog">
          <a href="https://space.bilibili.com/42339430" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-youtube"></i> <br />
            
            Vlog
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="#" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            Search
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup">
 <span class="search-icon fa fa-search"></span>
 <input type="text" id="local-search-input">
 <div id="local-search-result"></div>
 <span class="popup-btn-close">close</span>
</div>


    </div>
  
</nav>

 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  
  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                SSM(十八) 秒杀架构实践
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            <span class="post-meta-item-icon">
              <i class="fa fa-calendar-o"></i>
            </span>
            <span class="post-meta-item-text">Posted on</span>
            <time itemprop="dateCreated" datetime="2018-05-07T01:12:54+08:00" content="2018-05-07">
              2018-05-07
            </time>
          </span>

          
            <span class="post-category" >
              &nbsp; | &nbsp;
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">In</span>
              
                <span itemprop="about" itemscope itemtype="https://schema.org/Thing">
                  <a href="/categories/SSM/" itemprop="url" rel="index">
                    <span itemprop="name">SSM</span>
                  </a>
                </span>

                
                
                  , 
                

              
                <span itemprop="about" itemscope itemtype="https://schema.org/Thing">
                  <a href="/categories/SSM/Distributed-Tools/" itemprop="url" rel="index">
                    <span itemprop="name">Distributed Tools</span>
                  </a>
                </span>

                
                

              
            </span>
          

          
            
              <span class="post-comments-count">
                &nbsp; | &nbsp;
                <a href="/2018/05/07/ssm/SSM18-seconds-kill/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count disqus-comment-count" data-disqus-identifier="2018/05/07/ssm/SSM18-seconds-kill/" itemprop="commentsCount"></span>
                </a>
              </span>
            
          

          

          
          
             <span id="/2018/05/07/ssm/SSM18-seconds-kill/" class="leancloud_visitors" data-flag-title="SSM(十八) 秒杀架构实践">
               &nbsp; | &nbsp;
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               <span class="post-meta-item-text">visitors </span>
               <span class="leancloud-visitors-count"></span>
              </span>
          

          
              &nbsp; | &nbsp;
              <span class="page-pv">本文总阅读量
              <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>次
              </span>
          
        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <p><img src="https://i.loli.net/2019/05/08/5cd1d713e19ed.jpg" alt=""></p>
<h2 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h2><p>之前在 <a href="https://github.com/crossoverJie/Java-Interview/blob/master/MD/Spike.md" target="_blank" rel="external">Java-Interview</a> 中提到过秒杀架构的设计，这次基于其中的理论简单实现了一下。</p>
<blockquote>
<p>本次采用循序渐进的方式逐步提高性能达到并发秒杀的效果，文章较长请准备好瓜子板凳(liushuizhang😂)。</p>
</blockquote>
<p>本文所有涉及的代码：</p>
<ul>
<li><a href="https://github.com/crossoverJie/SSM" target="_blank" rel="external">https://github.com/crossoverJie/SSM</a></li>
<li><a href="https://github.com/crossoverJie/distributed-redis-tool" target="_blank" rel="external">https://github.com/crossoverJie/distributed-redis-tool</a></li>
</ul>
<p>最终架构图：</p>
<p><img src="https://i.loli.net/2018/05/08/5af079ea8618b.png" alt="系统架构设计.png"></p>
<a id="more"></a>
<p>先简单根据这个图谈下请求的流转，因为后面不管怎么改进这个都是没有变的。</p>
<ul>
<li>前端请求进入 <code>web</code> 层，对应的代码就是 <code>controller</code>。</li>
<li>之后将真正的库存校验、下单等请求发往 <code>Service</code> 层（其中 RPC 调用依然采用的 <code>dubbo</code>，只是更新为最新版本，本次不会过多讨论 dubbo 相关的细节，有兴趣的可以查看 <a href="https://crossoverjie.top/%2F2017%2F04%2F07%2FSSM11%2F">基于dubbo的分布式架构</a>）。</li>
<li><code>Service</code> 层再对数据进行落地，下单完成。</li>
</ul>
<h2 id="无限制"><a href="#无限制" class="headerlink" title="无限制"></a>无限制</h2><p>其实抛开秒杀这个场景来说正常的一个下单流程可以简单分为以下几步：</p>
<ul>
<li>校验库存</li>
<li>扣库存</li>
<li>创建订单</li>
<li>支付</li>
</ul>
<p>基于上文的架构所以我们有了以下实现：</p>
<p>先看看实际项目的结构：</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1d71693bb0.jpg" alt=""></p>
<p>还是和以前一样：</p>
<ul>
<li>提供出一个 <code>API</code> 用于 <code>Service</code> 层实现，以及 <code>web</code> 层消费。</li>
<li>web 层简单来说就是一个 <code>SpringMVC</code>。</li>
<li><code>Service</code> 层则是真正的数据落地。</li>
<li><code>SSM-SECONDS-KILL-ORDER-CONSUMER</code> 则是后文会提到的 <code>Kafka</code> 消费。</li>
</ul>
<p>数据库也是只有简单的两张表模拟下单：</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">CREATE</span> <span class="keyword">TABLE</span> <span class="string">`stock`</span> (</div><div class="line">  <span class="string">`id`</span> <span class="built_in">int</span>(<span class="number">11</span>) <span class="keyword">unsigned</span> <span class="keyword">NOT</span> <span class="literal">NULL</span> AUTO_INCREMENT,</div><div class="line">  <span class="string">`name`</span> <span class="built_in">varchar</span>(<span class="number">50</span>) <span class="keyword">NOT</span> <span class="literal">NULL</span> <span class="keyword">DEFAULT</span> <span class="string">''</span> <span class="keyword">COMMENT</span> <span class="string">'名称'</span>,</div><div class="line">  <span class="string">`count`</span> <span class="built_in">int</span>(<span class="number">11</span>) <span class="keyword">NOT</span> <span class="literal">NULL</span> <span class="keyword">COMMENT</span> <span class="string">'库存'</span>,</div><div class="line">  <span class="string">`sale`</span> <span class="built_in">int</span>(<span class="number">11</span>) <span class="keyword">NOT</span> <span class="literal">NULL</span> <span class="keyword">COMMENT</span> <span class="string">'已售'</span>,</div><div class="line">  <span class="string">`version`</span> <span class="built_in">int</span>(<span class="number">11</span>) <span class="keyword">NOT</span> <span class="literal">NULL</span> <span class="keyword">COMMENT</span> <span class="string">'乐观锁，版本号'</span>,</div><div class="line">  PRIMARY <span class="keyword">KEY</span> (<span class="string">`id`</span>)</div><div class="line">) <span class="keyword">ENGINE</span>=<span class="keyword">InnoDB</span> AUTO_INCREMENT=<span class="number">2</span> <span class="keyword">DEFAULT</span> <span class="keyword">CHARSET</span>=utf8;</div><div class="line"></div><div class="line"></div><div class="line"><span class="keyword">CREATE</span> <span class="keyword">TABLE</span> <span class="string">`stock_order`</span> (</div><div class="line">  <span class="string">`id`</span> <span class="built_in">int</span>(<span class="number">11</span>) <span class="keyword">unsigned</span> <span class="keyword">NOT</span> <span class="literal">NULL</span> AUTO_INCREMENT,</div><div class="line">  <span class="string">`sid`</span> <span class="built_in">int</span>(<span class="number">11</span>) <span class="keyword">NOT</span> <span class="literal">NULL</span> <span class="keyword">COMMENT</span> <span class="string">'库存ID'</span>,</div><div class="line">  <span class="string">`name`</span> <span class="built_in">varchar</span>(<span class="number">30</span>) <span class="keyword">NOT</span> <span class="literal">NULL</span> <span class="keyword">DEFAULT</span> <span class="string">''</span> <span class="keyword">COMMENT</span> <span class="string">'商品名称'</span>,</div><div class="line">  <span class="string">`create_time`</span> <span class="keyword">timestamp</span> <span class="keyword">NOT</span> <span class="literal">NULL</span> <span class="keyword">DEFAULT</span> <span class="keyword">CURRENT_TIMESTAMP</span> <span class="keyword">ON</span> <span class="keyword">UPDATE</span> <span class="keyword">CURRENT_TIMESTAMP</span> <span class="keyword">COMMENT</span> <span class="string">'创建时间'</span>,</div><div class="line">  PRIMARY <span class="keyword">KEY</span> (<span class="string">`id`</span>)</div><div class="line">) <span class="keyword">ENGINE</span>=<span class="keyword">InnoDB</span> AUTO_INCREMENT=<span class="number">55</span> <span class="keyword">DEFAULT</span> <span class="keyword">CHARSET</span>=utf8;</div></pre></td></tr></table></figure>
<p>web 层 <code>controller</code> 实现:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div></pre></td><td class="code"><pre><div class="line"></div><div class="line"><span class="meta">@Autowired</span></div><div class="line"><span class="keyword">private</span> StockService stockService;</div><div class="line"></div><div class="line"><span class="meta">@Autowired</span></div><div class="line"><span class="keyword">private</span> OrderService orderService;</div><div class="line"></div><div class="line"><span class="meta">@RequestMapping</span>(<span class="string">"/createWrongOrder/&#123;sid&#125;"</span>)</div><div class="line"><span class="meta">@ResponseBody</span></div><div class="line"><span class="function"><span class="keyword">public</span> String <span class="title">createWrongOrder</span><span class="params">(@PathVariable <span class="keyword">int</span> sid)</span> </span>&#123;</div><div class="line">    logger.info(<span class="string">"sid=[&#123;&#125;]"</span>, sid);</div><div class="line">    <span class="keyword">int</span> id = <span class="number">0</span>;</div><div class="line">    <span class="keyword">try</span> &#123;</div><div class="line">        id = orderService.createWrongOrder(sid);</div><div class="line">    &#125; <span class="keyword">catch</span> (Exception e) &#123;</div><div class="line">        logger.error(<span class="string">"Exception"</span>,e);</div><div class="line">    &#125;</div><div class="line">    <span class="keyword">return</span> String.valueOf(id);</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>其中 web 作为一个消费者调用看 <code>OrderService</code> 提供出来的 dubbo 服务。</p>
<p>Service 层，<code>OrderService</code> 实现：</p>
<p>首先是对 API 的实现(会在 API 提供出接口)：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div></pre></td><td class="code"><pre><div class="line"><span class="meta">@Service</span></div><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">OrderServiceImpl</span> <span class="keyword">implements</span> <span class="title">OrderService</span> </span>&#123;</div><div class="line"></div><div class="line">    <span class="meta">@Resource</span>(name = <span class="string">"DBOrderService"</span>)</div><div class="line">    <span class="keyword">private</span> com.crossoverJie.seconds.kill.service.OrderService orderService ;</div><div class="line"></div><div class="line">    <span class="meta">@Override</span></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">createWrongOrder</span><span class="params">(<span class="keyword">int</span> sid)</span> <span class="keyword">throws</span> Exception </span>&#123;</div><div class="line">        <span class="keyword">return</span> orderService.createWrongOrder(sid);</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>这里只是简单调用了 <code>DBOrderService</code> 中的实现，DBOrderService 才是真正的数据落地，也就是写数据库了。</p>
<p>DBOrderService 实现：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div></pre></td><td class="code"><pre><div class="line">Transactional(rollbackFor = Exception.class)</div><div class="line"><span class="meta">@Service</span>(value = <span class="string">"DBOrderService"</span>)</div><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">OrderServiceImpl</span> <span class="keyword">implements</span> <span class="title">OrderService</span> </span>&#123;</div><div class="line">    <span class="meta">@Resource</span>(name = <span class="string">"DBStockService"</span>)</div><div class="line">    <span class="keyword">private</span> com.crossoverJie.seconds.kill.service.StockService stockService;</div><div class="line"></div><div class="line">    <span class="meta">@Autowired</span></div><div class="line">    <span class="keyword">private</span> StockOrderMapper orderMapper;</div><div class="line">    </div><div class="line">    <span class="meta">@Override</span></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">createWrongOrder</span><span class="params">(<span class="keyword">int</span> sid)</span> <span class="keyword">throws</span> Exception</span>&#123;</div><div class="line"></div><div class="line">        <span class="comment">//校验库存</span></div><div class="line">        Stock stock = checkStock(sid);</div><div class="line"></div><div class="line">        <span class="comment">//扣库存</span></div><div class="line">        saleStock(stock);</div><div class="line"></div><div class="line">        <span class="comment">//创建订单</span></div><div class="line">        <span class="keyword">int</span> id = createOrder(stock);</div><div class="line"></div><div class="line">        <span class="keyword">return</span> id;</div><div class="line">    &#125;</div><div class="line">    </div><div class="line">    <span class="function"><span class="keyword">private</span> Stock <span class="title">checkStock</span><span class="params">(<span class="keyword">int</span> sid)</span> </span>&#123;</div><div class="line">        Stock stock = stockService.getStockById(sid);</div><div class="line">        <span class="keyword">if</span> (stock.getSale().equals(stock.getCount())) &#123;</div><div class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> RuntimeException(<span class="string">"库存不足"</span>);</div><div class="line">        &#125;</div><div class="line">        <span class="keyword">return</span> stock;</div><div class="line">    &#125;</div><div class="line">    </div><div class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">int</span> <span class="title">saleStock</span><span class="params">(Stock stock)</span> </span>&#123;</div><div class="line">        stock.setSale(stock.getSale() + <span class="number">1</span>);</div><div class="line">        <span class="keyword">return</span> stockService.updateStockById(stock);</div><div class="line">    &#125;</div><div class="line">    </div><div class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">int</span> <span class="title">createOrder</span><span class="params">(Stock stock)</span> </span>&#123;</div><div class="line">        StockOrder order = <span class="keyword">new</span> StockOrder();</div><div class="line">        order.setSid(stock.getId());</div><div class="line">        order.setName(stock.getName());</div><div class="line">        <span class="keyword">int</span> id = orderMapper.insertSelective(order);</div><div class="line">        <span class="keyword">return</span> id;</div><div class="line">    &#125;        </div><div class="line">        </div><div class="line">&#125;</div></pre></td></tr></table></figure>
<blockquote>
<p> 预先初始化了 10 条库存。</p>
</blockquote>
<p>手动调用下 <code>createWrongOrder/1</code> 接口发现：</p>
<p>库存表：<br><img src="https://i.loli.net/2019/05/08/5cd1d7189c72f.jpg" alt=""></p>
<p>订单表：<br><img src="https://i.loli.net/2019/05/08/5cd1d721e9fd4.jpg" alt=""></p>
<p>一切看起来都没有问题，数据也正常。</p>
<p>但是当用 <code>JMeter</code> 并发测试时：</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1d7243c657.jpg" alt=""></p>
<p>测试配置是：300个线程并发，测试两轮来看看数据库中的结果：</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1d726cee79.jpg" alt=""></p>
<p><img src="https://i.loli.net/2019/05/08/5cd1d72816d67.jpg" alt=""></p>
<p><img src="https://i.loli.net/2019/05/08/5cd1d72b9f26a.jpg" alt=""></p>
<p>请求都响应成功，库存确实也扣完了，但是订单却生成了 <strong>124</strong> 条记录。</p>
<p>这显然是典型的超卖现象。</p>
<blockquote>
<p>其实现在再去手动调用接口会返回库存不足，但为时晚矣。</p>
</blockquote>
<h2 id="乐观锁更新"><a href="#乐观锁更新" class="headerlink" title="乐观锁更新"></a>乐观锁更新</h2><p>怎么来避免上述的现象呢？</p>
<p>最简单的做法自然是乐观锁了，这里不过多讨论这个，不熟悉的朋友可以看下<a href="http://crossoverjie.top/%2F2017%2F07%2F09%2FSSM15%2F">这篇</a>。</p>
<p>来看看具体实现：</p>
<blockquote>
<p>其实其他的都没怎么改，主要是 Service 层。</p>
</blockquote>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div></pre></td><td class="code"><pre><div class="line"><span class="meta">@Override</span></div><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">createOptimisticOrder</span><span class="params">(<span class="keyword">int</span> sid)</span> <span class="keyword">throws</span> Exception </span>&#123;</div><div class="line"></div><div class="line">    <span class="comment">//校验库存</span></div><div class="line">    Stock stock = checkStock(sid);</div><div class="line"></div><div class="line">    <span class="comment">//乐观锁更新库存</span></div><div class="line">    saleStockOptimistic(stock);</div><div class="line"></div><div class="line">    <span class="comment">//创建订单</span></div><div class="line">    <span class="keyword">int</span> id = createOrder(stock);</div><div class="line"></div><div class="line">    <span class="keyword">return</span> id;</div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">saleStockOptimistic</span><span class="params">(Stock stock)</span> </span>&#123;</div><div class="line">    <span class="keyword">int</span> count = stockService.updateStockByOptimistic(stock);</div><div class="line">    <span class="keyword">if</span> (count == <span class="number">0</span>)&#123;</div><div class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> RuntimeException(<span class="string">"并发更新库存失败"</span>) ;</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>对应的 XML：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div></pre></td><td class="code"><pre><div class="line"><span class="tag">&lt;<span class="name">update</span> <span class="attr">id</span>=<span class="string">"updateByOptimistic"</span> <span class="attr">parameterType</span>=<span class="string">"com.crossoverJie.seconds.kill.pojo.Stock"</span>&gt;</span></div><div class="line">    update stock</div><div class="line">    <span class="tag">&lt;<span class="name">set</span>&gt;</span></div><div class="line">        sale = sale + 1,</div><div class="line">        version = version + 1,</div><div class="line">    <span class="tag">&lt;/<span class="name">set</span>&gt;</span></div><div class="line"></div><div class="line">    WHERE id = #&#123;id,jdbcType=INTEGER&#125;</div><div class="line">    AND version = #&#123;version,jdbcType=INTEGER&#125;</div><div class="line"></div><div class="line"><span class="tag">&lt;/<span class="name">update</span>&gt;</span></div></pre></td></tr></table></figure>
<p>同样的测试条件，我们再进行上面的测试 <code>/createOptimisticOrder/1</code>：</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1d72dab853.jpg" alt=""></p>
<p><img src="https://i.loli.net/2019/05/08/5cd1d730800b1.jpg" alt=""></p>
<p><img src="https://i.loli.net/2019/05/08/5cd1d73324dd2.jpg" alt=""></p>
<p>这次发现无论是库存订单都是 OK 的。</p>
<p>查看日志发现：</p>
<p><img src="https://i.loli.net//2019//05//08//5cd1daafb70bc.jpg" alt=""></p>
<p>很多并发请求会响应错误，这就达到了效果。</p>
<h3 id="提高吞吐量"><a href="#提高吞吐量" class="headerlink" title="提高吞吐量"></a>提高吞吐量</h3><p>为了进一步提高秒杀时的吞吐量以及响应效率，这里的 web 和 Service 都进行了横向扩展。</p>
<ul>
<li>web 利用 Nginx 进行负载。</li>
<li>Service 也是多台应用。</li>
</ul>
<p><img src="https://i.loli.net/2019/05/08/5cd1d752909b9.jpg" alt=""></p>
<p><img src="https://i.loli.net/2019/05/08/5cd1d758c7714.jpg" alt=""></p>
<p>再用 JMeter 测试时可以直观的看到效果。</p>
<blockquote>
<p>由于我是在阿里云的一台小水管服务器进行测试的，加上配置不高、应用都在同一台，所以并没有完全体现出性能上的优势（ <code>Nginx</code> 做负载转发时候也会增加额外的网络消耗）。</p>
</blockquote>
<h3 id="shell-脚本实现简单的-CI"><a href="#shell-脚本实现简单的-CI" class="headerlink" title="shell 脚本实现简单的 CI"></a>shell 脚本实现简单的 CI</h3><p>由于应用多台部署之后，手动发版测试的痛苦相信经历过的都有体会。</p>
<p>这次并没有精力去搭建完整的 CI CD，只是写了一个简单的脚本实现了自动化部署，希望对这方面没有经验的同学带来一点启发：</p>
<h4 id="构建-web"><a href="#构建-web" class="headerlink" title="构建 web"></a>构建 web</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div></pre></td><td class="code"><pre><div class="line">#!/bin/bash</div><div class="line"></div><div class="line"># 构建 web 消费者</div><div class="line"></div><div class="line">#read appname</div><div class="line"></div><div class="line">appname=&quot;consumer&quot;</div><div class="line">echo &quot;input=&quot;$appname</div><div class="line"></div><div class="line">PID=$(ps -ef | grep $appname | grep -v grep | awk &apos;&#123;print $2&#125;&apos;)</div><div class="line"></div><div class="line"># 遍历杀掉 pid</div><div class="line">for var in $&#123;PID[@]&#125;;</div><div class="line">do</div><div class="line">    echo &quot;loop pid= $var&quot;</div><div class="line">    kill -9 $var</div><div class="line">done</div><div class="line"></div><div class="line">echo &quot;kill $appname success&quot;</div><div class="line"></div><div class="line">cd ..</div><div class="line"></div><div class="line">git pull</div><div class="line"></div><div class="line">cd SSM-SECONDS-KILL</div><div class="line"></div><div class="line">mvn -Dmaven.test.skip=true clean package</div><div class="line"></div><div class="line">echo &quot;build war success&quot;</div><div class="line"></div><div class="line">cp /home/crossoverJie/SSM/SSM-SECONDS-KILL/SSM-SECONDS-KILL-WEB/target/SSM-SECONDS-KILL-WEB-2.2.0-SNAPSHOT.war /home/crossoverJie/tomcat/tomcat-dubbo-consumer-8083/webapps</div><div class="line">echo &quot;cp tomcat-dubbo-consumer-8083/webapps ok!&quot;</div><div class="line"></div><div class="line">cp /home/crossoverJie/SSM/SSM-SECONDS-KILL/SSM-SECONDS-KILL-WEB/target/SSM-SECONDS-KILL-WEB-2.2.0-SNAPSHOT.war /home/crossoverJie/tomcat/tomcat-dubbo-consumer-7083-slave/webapps</div><div class="line">echo &quot;cp tomcat-dubbo-consumer-7083-slave/webapps ok!&quot;</div><div class="line"></div><div class="line">sh /home/crossoverJie/tomcat/tomcat-dubbo-consumer-8083/bin/startup.sh</div><div class="line">echo &quot;tomcat-dubbo-consumer-8083/bin/startup.sh success&quot;</div><div class="line"></div><div class="line">sh /home/crossoverJie/tomcat/tomcat-dubbo-consumer-7083-slave/bin/startup.sh</div><div class="line">echo &quot;tomcat-dubbo-consumer-7083-slave/bin/startup.sh success&quot;</div><div class="line"></div><div class="line">echo &quot;start $appname success&quot;</div></pre></td></tr></table></figure>
<h4 id="构建-Service"><a href="#构建-Service" class="headerlink" title="构建 Service"></a>构建 Service</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div><div class="line">50</div><div class="line">51</div><div class="line">52</div><div class="line">53</div></pre></td><td class="code"><pre><div class="line"># 构建服务提供者</div><div class="line"></div><div class="line">#read appname</div><div class="line"></div><div class="line">appname=&quot;provider&quot;</div><div class="line"></div><div class="line">echo &quot;input=&quot;$appname</div><div class="line"></div><div class="line"></div><div class="line">PID=$(ps -ef | grep $appname | grep -v grep | awk &apos;&#123;print $2&#125;&apos;)</div><div class="line"></div><div class="line">#if [ $? -eq 0 ]; then</div><div class="line">#    echo &quot;process id:$PID&quot;</div><div class="line">#else</div><div class="line">#    echo &quot;process $appname not exit&quot;</div><div class="line">#    exit</div><div class="line">#fi</div><div class="line"></div><div class="line"># 遍历杀掉 pid</div><div class="line">for var in $&#123;PID[@]&#125;;</div><div class="line">do</div><div class="line">    echo &quot;loop pid= $var&quot;</div><div class="line">    kill -9 $var</div><div class="line">done</div><div class="line"></div><div class="line">echo &quot;kill $appname success&quot;</div><div class="line"></div><div class="line"></div><div class="line">cd ..</div><div class="line"></div><div class="line">git pull</div><div class="line"></div><div class="line">cd SSM-SECONDS-KILL</div><div class="line"></div><div class="line">mvn -Dmaven.test.skip=true clean package</div><div class="line"></div><div class="line">echo &quot;build war success&quot;</div><div class="line"></div><div class="line">cp /home/crossoverJie/SSM/SSM-SECONDS-KILL/SSM-SECONDS-KILL-SERVICE/target/SSM-SECONDS-KILL-SERVICE-2.2.0-SNAPSHOT.war /home/crossoverJie/tomcat/tomcat-dubbo-provider-8080/webapps</div><div class="line"></div><div class="line">echo &quot;cp tomcat-dubbo-provider-8080/webapps ok!&quot;</div><div class="line"></div><div class="line">cp /home/crossoverJie/SSM/SSM-SECONDS-KILL/SSM-SECONDS-KILL-SERVICE/target/SSM-SECONDS-KILL-SERVICE-2.2.0-SNAPSHOT.war /home/crossoverJie/tomcat/tomcat-dubbo-provider-7080-slave/webapps</div><div class="line"></div><div class="line">echo &quot;cp tomcat-dubbo-provider-7080-slave/webapps ok!&quot;</div><div class="line"></div><div class="line">sh /home/crossoverJie/tomcat/tomcat-dubbo-provider-8080/bin/startup.sh</div><div class="line">echo &quot;tomcat-dubbo-provider-8080/bin/startup.sh success&quot;</div><div class="line"></div><div class="line">sh /home/crossoverJie/tomcat/tomcat-dubbo-provider-7080-slave/bin/startup.sh</div><div class="line">echo &quot;tomcat-dubbo-provider-8080/bin/startup.sh success&quot;</div><div class="line"></div><div class="line">echo &quot;start $appname success&quot;</div></pre></td></tr></table></figure>
<p>之后每当我有更新，只需要执行这两个脚本就可以帮我自动构建。</p>
<p>都是最基础的 Linux 命令，相信大家都看得明白。</p>
<h2 id="乐观锁更新-分布式限流"><a href="#乐观锁更新-分布式限流" class="headerlink" title="乐观锁更新 + 分布式限流"></a>乐观锁更新 + 分布式限流</h2><p>上文的结果看似没有问题，其实还差得远呢。</p>
<p>这里只是模拟了 300 个并发没有问题，但是当请求达到了 3000 ，3W，300W 呢？</p>
<p>虽说可以横向扩展可以支撑更多的请求。</p>
<p>但是能不能利用最少的资源解决问题呢？</p>
<p>其实仔细分析下会发现：</p>
<blockquote>
<p>假设我的商品一共只有 10 个库存，那么无论你多少人来买其实最终也最多只有 10 人可以下单成功。</p>
</blockquote>
<p>所以其中会有 <code>99%</code> 的请求都是无效的。</p>
<p>大家都知道：大多数应用数据库都是压倒骆驼的最后一根稻草。</p>
<p>通过 <code>Druid</code> 的监控来看看之前请求数据库的情况：</p>
<p>因为 Service 是两个应用。<br><img src="https://i.loli.net/2019/05/08/5cd1d764221b5.jpg" alt=""></p>
<p><img src="https://i.loli.net/2019/05/08/5cd1d7676e1d2.jpg" alt=""></p>
<p><img src="https://i.loli.net//2019//05//08//5cd1daeb0c306.jpg" alt=""></p>
<p>数据库也有 20 多个连接。</p>
<p>怎么样来优化呢？<br>其实很容易想到的就是<a href="http://crossoverjie.top/2018/04/28/sbc/sbc7-Distributed-Limit/">分布式限流</a>。</p>
<p>我们将并发控制在一个可控的范围之内，然后快速失败这样就能最大程度的保护系统。</p>
<h3 id="distributed-redis-tool-⬆️v1-0-3"><a href="#distributed-redis-tool-⬆️v1-0-3" class="headerlink" title="distributed-redis-tool ⬆️v1.0.3"></a>distributed-redis-tool ⬆️v1.0.3</h3><p>为此还对 <a href="https://github.com/crossoverJie/distributed-redis-tool" target="_blank" rel="external">https://github.com/crossoverJie/distributed-redis-tool</a> 进行了小小的升级。</p>
<p>因为加上该组件之后所有的请求都会经过 Redis，所以对 Redis 资源的使用也是要非常小心。</p>
<h4 id="API-更新"><a href="#API-更新" class="headerlink" title="API 更新"></a>API 更新</h4><p>修改之后的 API 如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div></pre></td><td class="code"><pre><div class="line"><span class="meta">@Configuration</span></div><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">RedisLimitConfig</span> </span>&#123;</div><div class="line"></div><div class="line">    <span class="keyword">private</span> Logger logger = LoggerFactory.getLogger(RedisLimitConfig.class);</div><div class="line"></div><div class="line">    <span class="meta">@Value</span>(<span class="string">"$&#123;redis.limit&#125;"</span>)</div><div class="line">    <span class="keyword">private</span> <span class="keyword">int</span> limit;</div><div class="line"></div><div class="line"></div><div class="line">    <span class="meta">@Autowired</span></div><div class="line">    <span class="keyword">private</span> JedisConnectionFactory jedisConnectionFactory;</div><div class="line"></div><div class="line">    <span class="meta">@Bean</span></div><div class="line">    <span class="function"><span class="keyword">public</span> RedisLimit <span class="title">build</span><span class="params">()</span> </span>&#123;</div><div class="line">        RedisLimit redisLimit = <span class="keyword">new</span> RedisLimit.Builder(jedisConnectionFactory, RedisToolsConstant.SINGLE)</div><div class="line">                .limit(limit)</div><div class="line">                .build();</div><div class="line"></div><div class="line">        <span class="keyword">return</span> redisLimit;</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>这里构建器改用了 <code>JedisConnectionFactory</code>，所以得配合 Spring 来一起使用。</p>
<p>并在初始化时显示传入 Redis 是以集群方式部署还是单机（强烈建议集群，限流之后对 Redis 还是有一定的压力）。</p>
<h5 id="限流实现"><a href="#限流实现" class="headerlink" title="限流实现"></a>限流实现</h5><p>既然 API 更新了，实现自然也要修改：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div></pre></td><td class="code"><pre><div class="line"><span class="comment">/**</span></div><div class="line"> * limit traffic</div><div class="line"> * <span class="doctag">@return</span> if true</div><div class="line"> */</div><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">limit</span><span class="params">()</span> </span>&#123;</div><div class="line"></div><div class="line">    <span class="comment">//get connection</span></div><div class="line">    Object connection = getConnection();</div><div class="line"></div><div class="line">    Object result = limitRequest(connection);</div><div class="line"></div><div class="line">    <span class="keyword">if</span> (FAIL_CODE != (Long) result) &#123;</div><div class="line">        <span class="keyword">return</span> <span class="keyword">true</span>;</div><div class="line">    &#125; <span class="keyword">else</span> &#123;</div><div class="line">        <span class="keyword">return</span> <span class="keyword">false</span>;</div><div class="line">    &#125;</div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="function"><span class="keyword">private</span> Object <span class="title">limitRequest</span><span class="params">(Object connection)</span> </span>&#123;</div><div class="line">    Object result = <span class="keyword">null</span>;</div><div class="line">    String key = String.valueOf(System.currentTimeMillis() / <span class="number">1000</span>);</div><div class="line">    <span class="keyword">if</span> (connection <span class="keyword">instanceof</span> Jedis)&#123;</div><div class="line">        result = ((Jedis)connection).eval(script, Collections.singletonList(key), Collections.singletonList(String.valueOf(limit)));</div><div class="line">        ((Jedis) connection).close();</div><div class="line">    &#125;<span class="keyword">else</span> &#123;</div><div class="line">        result = ((JedisCluster) connection).eval(script, Collections.singletonList(key), Collections.singletonList(String.valueOf(limit)));</div><div class="line">        <span class="keyword">try</span> &#123;</div><div class="line">            ((JedisCluster) connection).close();</div><div class="line">        &#125; <span class="keyword">catch</span> (IOException e) &#123;</div><div class="line">            logger.error(<span class="string">"IOException"</span>,e);</div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line">    <span class="keyword">return</span> result;</div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="function"><span class="keyword">private</span> Object <span class="title">getConnection</span><span class="params">()</span> </span>&#123;</div><div class="line">    Object connection ;</div><div class="line">    <span class="keyword">if</span> (type == RedisToolsConstant.SINGLE)&#123;</div><div class="line">        RedisConnection redisConnection = jedisConnectionFactory.getConnection();</div><div class="line">        connection = redisConnection.getNativeConnection();</div><div class="line">    &#125;<span class="keyword">else</span> &#123;</div><div class="line">        RedisClusterConnection clusterConnection = jedisConnectionFactory.getClusterConnection();</div><div class="line">        connection = clusterConnection.getNativeConnection() ;</div><div class="line">    &#125;</div><div class="line">    <span class="keyword">return</span> connection;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>如果是原生的 Spring 应用得采用 <code>@SpringControllerLimit(errorCode = 200)</code> 注解。</p>
<p>实际使用如下：</p>
<p>web 端：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div></pre></td><td class="code"><pre><div class="line"><span class="comment">/**</span></div><div class="line"> * 乐观锁更新库存 限流</div><div class="line"> * <span class="doctag">@param</span> sid</div><div class="line"> * <span class="doctag">@return</span></div><div class="line"> */</div><div class="line"><span class="meta">@SpringControllerLimit</span>(errorCode = <span class="number">200</span>)</div><div class="line"><span class="meta">@RequestMapping</span>(<span class="string">"/createOptimisticLimitOrder/&#123;sid&#125;"</span>)</div><div class="line"><span class="meta">@ResponseBody</span></div><div class="line"><span class="function"><span class="keyword">public</span> String <span class="title">createOptimisticLimitOrder</span><span class="params">(@PathVariable <span class="keyword">int</span> sid)</span> </span>&#123;</div><div class="line">    logger.info(<span class="string">"sid=[&#123;&#125;]"</span>, sid);</div><div class="line">    <span class="keyword">int</span> id = <span class="number">0</span>;</div><div class="line">    <span class="keyword">try</span> &#123;</div><div class="line">        id = orderService.createOptimisticOrder(sid);</div><div class="line">    &#125; <span class="keyword">catch</span> (Exception e) &#123;</div><div class="line">        logger.error(<span class="string">"Exception"</span>,e);</div><div class="line">    &#125;</div><div class="line">    <span class="keyword">return</span> String.valueOf(id);</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>Service 端就没什么更新了，依然是采用的乐观锁更新数据库。</p>
<p>再压测看下效果 <code>/createOptimisticLimitOrderByRedis/1</code>：</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1d776c39b7.jpg" alt=""></p>
<p><img src="https://i.loli.net/2019/05/08/5cd1d77ba16d2.jpg" alt=""></p>
<p><img src="https://i.loli.net/2019/05/08/5cd1d780d5aa2.jpg" alt=""></p>
<p><img src="https://i.loli.net/2019/05/08/5cd1d784644d5.jpg" alt=""></p>
<p><img src="https://i.loli.net/2019/05/08/5cd1d787b3e49.jpg" alt=""></p>
<p>首先是看结果没有问题，再看数据库连接以及并发请求数都有<strong>明显的下降</strong>。</p>
<h2 id="乐观锁更新-分布式限流-Redis-缓存"><a href="#乐观锁更新-分布式限流-Redis-缓存" class="headerlink" title="乐观锁更新 + 分布式限流 + Redis 缓存"></a>乐观锁更新 + 分布式限流 + Redis 缓存</h2><p>其实仔细观察 Druid 监控数据发现这个 SQL 被多次查询：</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1d78b3896a.jpg" alt=""></p>
<p>其实这是实时查询库存的 SQL，主要是为了在每次下单之前判断是否还有库存。</p>
<p><strong>这也是个优化点</strong>。</p>
<p>这种数据我们完全可以放在内存中，效率比在数据库要高很多。</p>
<p>由于我们的应用是分布式的，所以堆内缓存显然不合适，Redis 就非常适合。</p>
<p>这次主要改造的是 Service 层：</p>
<ul>
<li>每次查询库存时走 Redis。</li>
<li>扣库存时更新 Redis。</li>
<li>需要提前将库存信息写入 Redis（手动或者程序自动都可以）。</li>
</ul>
<p>主要代码如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div></pre></td><td class="code"><pre><div class="line"><span class="meta">@Override</span></div><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">createOptimisticOrderUseRedis</span><span class="params">(<span class="keyword">int</span> sid)</span> <span class="keyword">throws</span> Exception </span>&#123;</div><div class="line">    <span class="comment">//检验库存，从 Redis 获取</span></div><div class="line">    Stock stock = checkStockByRedis(sid);</div><div class="line"></div><div class="line">    <span class="comment">//乐观锁更新库存 以及更新 Redis</span></div><div class="line">    saleStockOptimisticByRedis(stock);</div><div class="line"></div><div class="line">    <span class="comment">//创建订单</span></div><div class="line">    <span class="keyword">int</span> id = createOrder(stock);</div><div class="line">    <span class="keyword">return</span> id ;</div><div class="line">&#125;</div><div class="line"></div><div class="line"></div><div class="line"><span class="function"><span class="keyword">private</span> Stock <span class="title">checkStockByRedis</span><span class="params">(<span class="keyword">int</span> sid)</span> <span class="keyword">throws</span> Exception </span>&#123;</div><div class="line">    Integer count = Integer.parseInt(redisTemplate.opsForValue().get(RedisKeysConstant.STOCK_COUNT + sid));</div><div class="line">    Integer sale = Integer.parseInt(redisTemplate.opsForValue().get(RedisKeysConstant.STOCK_SALE + sid));</div><div class="line">    <span class="keyword">if</span> (count.equals(sale))&#123;</div><div class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> RuntimeException(<span class="string">"库存不足 Redis currentCount="</span> + sale);</div><div class="line">    &#125;</div><div class="line">    Integer version = Integer.parseInt(redisTemplate.opsForValue().get(RedisKeysConstant.STOCK_VERSION + sid));</div><div class="line">    Stock stock = <span class="keyword">new</span> Stock() ;</div><div class="line">    stock.setId(sid);</div><div class="line">    stock.setCount(count);</div><div class="line">    stock.setSale(sale);</div><div class="line">    stock.setVersion(version);</div><div class="line"></div><div class="line">    <span class="keyword">return</span> stock;</div><div class="line">&#125;    </div><div class="line"></div><div class="line"></div><div class="line"><span class="comment">/**</span></div><div class="line"> * 乐观锁更新数据库 还要更新 Redis</div><div class="line"> * <span class="doctag">@param</span> stock</div><div class="line"> */</div><div class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">saleStockOptimisticByRedis</span><span class="params">(Stock stock)</span> </span>&#123;</div><div class="line">    <span class="keyword">int</span> count = stockService.updateStockByOptimistic(stock);</div><div class="line">    <span class="keyword">if</span> (count == <span class="number">0</span>)&#123;</div><div class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> RuntimeException(<span class="string">"并发更新库存失败"</span>) ;</div><div class="line">    &#125;</div><div class="line">    <span class="comment">//自增</span></div><div class="line">    redisTemplate.opsForValue().increment(RedisKeysConstant.STOCK_SALE + stock.getId(),<span class="number">1</span>) ;</div><div class="line">    redisTemplate.opsForValue().increment(RedisKeysConstant.STOCK_VERSION + stock.getId(),<span class="number">1</span>) ;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>压测看看实际效果 <code>/createOptimisticLimitOrderByRedis/1</code>：</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1d78d659b6.jpg" alt=""></p>
<p><img src="https://i.loli.net/2019/05/08/5cd1d790607a1.jpg" alt=""></p>
<p><img src="https://i.loli.net/2019/05/08/5cd1d79307676.jpg" alt=""></p>
<p><img src="https://i.loli.net/2019/05/08/5cd1d7973de43.jpg" alt=""></p>
<p>最后发现数据没问题，数据库的请求与并发也都下来了。</p>
<h2 id="乐观锁更新-分布式限流-Redis-缓存-Kafka-异步"><a href="#乐观锁更新-分布式限流-Redis-缓存-Kafka-异步" class="headerlink" title="乐观锁更新 + 分布式限流 + Redis 缓存 + Kafka 异步"></a>乐观锁更新 + 分布式限流 + Redis 缓存 + Kafka 异步</h2><p>最后的优化还是想如何来再次提高吞吐量以及性能的。</p>
<p>我们上文所有例子其实都是同步请求，完全可以利用同步转异步来提高性能啊。</p>
<p>这里我们将写订单以及更新库存的操作进行异步化，利用 <code>Kafka</code> 来进行解耦和队列的作用。</p>
<p>每当一个请求通过了限流到达了 Service 层通过了库存校验之后就将订单信息发给 Kafka ，这样一个请求就可以直接返回了。</p>
<p>消费程序再对数据进行入库落地。</p>
<p>因为异步了，所以最终需要采取回调或者是其他提醒的方式提醒用户购买完成。</p>
<p>这里代码较多就不贴了，消费程序其实就是把之前的 Service 层的逻辑重写了一遍，不过采用的是 SpringBoot。</p>
<p>感兴趣的朋友可以看下。</p>
<p><a href="https://github.com/crossoverJie/SSM/tree/master/SSM-SECONDS-KILL/SSM-SECONDS-KILL-ORDER-CONSUMER" target="_blank" rel="external">https://github.com/crossoverJie/SSM/tree/master/SSM-SECONDS-KILL/SSM-SECONDS-KILL-ORDER-CONSUMER</a></p>
<h2 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h2><p>其实经过上面的一顿优化总结起来无非就是以下几点：</p>
<ul>
<li>尽量将请求拦截在上游。</li>
<li>还可以根据 UID 进行限流。</li>
<li>最大程度的减少请求落到 DB。</li>
<li>多利用缓存。</li>
<li>同步操作异步化。</li>
<li>fail fast，尽早失败，保护应用。</li>
</ul>
<p>码字不易，这应该是我写过字数最多的了，想想当年高中 800 字的作文都憋不出来😂，可想而知是有多难得了。</p>
<p><strong>以上内容欢迎讨论</strong>。</p>
<h3 id="号外"><a href="#号外" class="headerlink" title="号外"></a>号外</h3><p>最近在总结一些 Java 相关的知识点，感兴趣的朋友可以一起维护。</p>
<blockquote>
<p>地址: <a href="https://github.com/crossoverJie/Java-Interview" target="_blank" rel="external">https://github.com/crossoverJie/Java-Interview</a></p>
</blockquote>

      
    </div>

    <div>
      
        
<div id="wechat_subscriber" style="display: block； padding: 10px 0; margin: 20px auto; width: 100%; text-align: center">
    <img id="wechat_subscriber_qcode" src="/uploads/weixinfooter1.jpg" alt="crossoverJie wechat" style="width: 200px; max-width: 100%;"/>
    <div>我很有眼光！</div>
</div>

      
    </div>

    <div>
      
        
  <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
    <div>请我吃🍗</div>
    <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
      <span>赏</span>
    </button>
    <div id="QR" style="display: none;">
      
        <div id="wechat" style="display: inline-block">
          <img id="wechat_qr" src="/weixin-reward-image.jpg" alt="crossoverJie WeChat Pay"/>
          <p>微信打赏</p>
        </div>
      
      
        <div id="alipay" style="display: inline-block">
          <img id="alipay_qr" src="/alipay-reward-image.jpg" alt="crossoverJie Alipay"/>
          <p>支付宝打赏</p>
        </div>
      
    </div>
  </div>


      
    </div>

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Java/" rel="tag">#Java</a>
          
            <a href="/tags/Kafka/" rel="tag">#Kafka</a>
          
            <a href="/tags/Redis/" rel="tag">#Redis</a>
          
            <a href="/tags/SpringBoot/" rel="tag">#SpringBoot</a>
          
        </div>
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/04/28/sbc/sbc7-Distributed-Limit/" rel="next" title="sbc(七)分布式限流">
                <i class="fa fa-chevron-left"></i> sbc(七)分布式限流
              </a>
            
          </div>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018/05/15/skill/1Kstar/" rel="prev" title="1K star+ 的项目是如何炼成的？">
                1K star+ 的项目是如何炼成的？ <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          

  <p>热评文章</p>
  <div class="ds-top-threads" data-range="weekly" data-num-items="4"></div>


          
  <div class="comments" id="comments">
    
      <div id="disqus_thread">
        <noscript>
          Please enable JavaScript to view the
          <a href="//disqus.com/?ref_noscript">comments powered by Disqus.</a>
        </noscript>
      </div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            Table of Contents
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            Overview
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel ">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/uploads/crossoverjie.jpg"
               alt="crossoverJie" />
          <p class="site-author-name" itemprop="name">crossoverJie</p>
          <p class="site-description motion-element" itemprop="description">You never know what you can do till you try.</p>
        </div>
        <nav class="site-state motion-element">
          <div class="site-state-item site-state-posts">
            <a href="/archives">
              <span class="site-state-item-count">116</span>
              <span class="site-state-item-name">posts</span>
            </a>
          </div>

          
            <div class="site-state-item site-state-categories">
              <a href="/categories">
                <span class="site-state-item-count">45</span>
                <span class="site-state-item-name">categories</span>
              </a>
            </div>
          

          
            <div class="site-state-item site-state-tags">
              <a href="/tags">
                <span class="site-state-item-count">109</span>
                <span class="site-state-item-name">tags</span>
              </a>
            </div>
          

        </nav>

        
          <div class="feed-link motion-element">
            <a href="/atom.xml" rel="alternate">
              <i class="fa fa-rss"></i>
              RSS
            </a>
          </div>
        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/crossoverJie" target="_blank" title="GitHub">
                  
                    <i class="fa fa-fw fa-github"></i>
                  
                  GitHub
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://www.jianshu.com/users/e2d07947c112/latest_articles" target="_blank" title="简书">
                  
                    <i class="fa fa-fw fa-book"></i>
                  
                  简书
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://juejin.im/user/576d4aaf7db2a20054ea4544" target="_blank" title="掘金">
                  
                    <i class="fa fa-fw fa-bookmark"></i>
                  
                  掘金
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://twitter.com/crossoverJie" target="_blank" title="Twitter">
                  
                    <i class="fa fa-fw fa-twitter"></i>
                  
                  Twitter
                </a>
              </span>
            
          
        </div>

        
        

        
        
          <div class="links-of-blogroll motion-element links-of-blogroll-inline">
            <div class="links-of-blogroll-title">
              <i class="fa  fa-fw fa-globe"></i>
              友情链接
            </div>
            <ul class="links-of-blogroll-list">
              
                <li class="links-of-blogroll-item">
                  <a href="http://wuchong.me" title="Jark's Blog" target="_blank">Jark's Blog</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://tengj.top" title="嘟嘟独立博客" target="_blank">嘟嘟独立博客</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://yemengying.com/" title="Giraffe Home" target="_blank">Giraffe Home</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="https://blog.jamespan.me/" title="潘小鶸(ruò)" target="_blank">潘小鶸(ruò)</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://fangjian0423.github.io/" title="Format's Notes" target="_blank">Format's Notes</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="https://yuzhouwan.com/" title="Benedict Jin" target="_blank">Benedict Jin</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://blog.didispace.com/" title="程序猿DD" target="_blank">程序猿DD</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="https://blog.52itstyle.vip/" title="小柒博客" target="_blank">小柒博客</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://cmsblogs.com/" title="Java技术驿站" target="_blank">Java技术驿站</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="https://vim.ink/" title="vim 教程网" target="_blank">vim 教程网</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="https://www.jitwxs.cn" title="jitwxs" target="_blank">jitwxs</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://www.javaboy.org" title="江南一点雨" target="_blank">江南一点雨</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://www.liangsonghua.me" title="松花皮蛋的黑板报" target="_blank">松花皮蛋的黑板报</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="https://www.fi-ads.com" title="Future iDeal" target="_blank">Future iDeal</a>
                </li>
              
            </ul>
          </div>
        

      </section>

      
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">
            
              
            
            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#前言"><span class="nav-number">1.</span> <span class="nav-text">前言</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#无限制"><span class="nav-number">2.</span> <span class="nav-text">无限制</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#乐观锁更新"><span class="nav-number">3.</span> <span class="nav-text">乐观锁更新</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#提高吞吐量"><span class="nav-number">3.1.</span> <span class="nav-text">提高吞吐量</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#shell-脚本实现简单的-CI"><span class="nav-number">3.2.</span> <span class="nav-text">shell 脚本实现简单的 CI</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#构建-web"><span class="nav-number">3.2.1.</span> <span class="nav-text">构建 web</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#构建-Service"><span class="nav-number">3.2.2.</span> <span class="nav-text">构建 Service</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#乐观锁更新-分布式限流"><span class="nav-number">4.</span> <span class="nav-text">乐观锁更新 + 分布式限流</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#distributed-redis-tool-⬆️v1-0-3"><span class="nav-number">4.1.</span> <span class="nav-text">distributed-redis-tool ⬆️v1.0.3</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#API-更新"><span class="nav-number">4.1.1.</span> <span class="nav-text">API 更新</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#限流实现"><span class="nav-number">4.1.1.1.</span> <span class="nav-text">限流实现</span></a></li></ol></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#乐观锁更新-分布式限流-Redis-缓存"><span class="nav-number">5.</span> <span class="nav-text">乐观锁更新 + 分布式限流 + Redis 缓存</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#乐观锁更新-分布式限流-Redis-缓存-Kafka-异步"><span class="nav-number">6.</span> <span class="nav-text">乐观锁更新 + 分布式限流 + Redis 缓存 + Kafka 异步</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#总结"><span class="nav-number">7.</span> <span class="nav-text">总结</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#号外"><span class="nav-number">7.1.</span> <span class="nav-text">号外</span></a></li></ol></li></ol></div>
            
          </div>
        </section>
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy;  2016 - 
  <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">crossoverJie</span>
</div>

<div class="powered-by">
  Powered by <a class="theme-link" href="http://hexo.io">Hexo</a>
</div>

<div class="theme-info">
  Theme -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Pisces
  </a>
</div>

        

<div class="busuanzi-count">

  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv"><i class="fa fa-user"></i><span class="busuanzi-value" id="busuanzi_value_site_uv"></span>人数</span>
  

  
    <span class="site-pv">您是第<span class="busuanzi-value" id="busuanzi_value_site_pv"></span>位童鞋</span>
  
  
</div>



        
      </div>
    </footer>

    <div class="back-to-top">
      <i class="fa fa-arrow-up"></i>
    </div>
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  



  
  <script type="text/javascript" src="/vendors/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/vendors/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/vendors/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/vendors/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/vendors/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/vendors/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.0.1"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.0.1"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.0.1"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.0.1"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.0.1"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.0.1"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.0.1"></script>



  



  

    <script type="text/javascript">
      var disqus_shortname = 'crossoverjie';
      var disqus_identifier = '2018/05/07/ssm/SSM18-seconds-kill/';
      var disqus_title = "SSM(十八) 秒杀架构实践";
      var disqus_url = 'http://crossoverjie.top/2018/05/07/ssm/SSM18-seconds-kill/';

      function run_disqus_script(disqus_script){
        var dsq = document.createElement('script');
        dsq.type = 'text/javascript';
        dsq.async = true;
        dsq.src = '//' + disqus_shortname + '.disqus.com/' + disqus_script;
        (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
      }

      run_disqus_script('count.js');
      
        run_disqus_script('embed.js');
      
    </script>
  




  
  
  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length == 0) {
       search_path = "search.xml";
    }
    var path = "/" + search_path;
    // monitor main search box;

    function proceedsearch() {
      $("body").append('<div class="popoverlay">').css('overflow', 'hidden');
      $('.popup').toggle();

    }
    // search function;
    var searchFunc = function(path, search_id, content_id) {
    'use strict';
    $.ajax({
        url: path,
        dataType: "xml",
        async: true,
        success: function( xmlResponse ) {
            // get the contents from search data
            isfetched = true;
            $('.popup').detach().appendTo('.header-inner');
            var datas = $( "entry", xmlResponse ).map(function() {
                return {
                    title: $( "title", this ).text(),
                    content: $("content",this).text(),
                    url: $( "url" , this).text()
                };
            }).get();
            var $input = document.getElementById(search_id);
            var $resultContent = document.getElementById(content_id);
            $input.addEventListener('input', function(){
                var matchcounts = 0;
                var str='<ul class=\"search-result-list\">';                
                var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
                $resultContent.innerHTML = "";
                if (this.value.trim().length > 1) {
                // perform local searching
                datas.forEach(function(data) {
                    var isMatch = true;
                    var content_index = [];
                    var data_title = data.title.trim().toLowerCase();
                    var data_content = data.content.trim().replace(/<[^>]+>/g,"").toLowerCase();
                    var data_url = data.url;
                    var index_title = -1;
                    var index_content = -1;
                    var first_occur = -1;
                    // only match artiles with not empty titles and contents
                    if(data_title != '' && data_content != '') {
                        keywords.forEach(function(keyword, i) {
                            index_title = data_title.indexOf(keyword);
                            index_content = data_content.indexOf(keyword);
                            if( index_title < 0 && index_content < 0 ){
                                isMatch = false;
                            } else {
                                if (index_content < 0) {
                                    index_content = 0;
                                }
                                if (i == 0) {
                                    first_occur = index_content;
                                }
                            }
                        });
                    }
                    // show search results
                    if (isMatch) {
                        matchcounts += 1;
                        str += "<li><a href='"+ data_url +"' class='search-result-title'>"+ data_title +"</a>";
                        var content = data.content.trim().replace(/<[^>]+>/g,"");
                        if (first_occur >= 0) {
                            // cut out 100 characters
                            var start = first_occur - 20;
                            var end = first_occur + 80;
                            if(start < 0){
                                start = 0;
                            }
                            if(start == 0){
                                end = 50;
                            }
                            if(end > content.length){
                                end = content.length;
                            }
                            var match_content = content.substring(start, end);
                            // highlight all keywords
                            keywords.forEach(function(keyword){
                                var regS = new RegExp(keyword, "gi");
                                match_content = match_content.replace(regS, "<b class=\"search-keyword\">"+keyword+"</b>");
                            });
                            
                            str += "<p class=\"search-result\">" + match_content +"...</p>"
                        }
                        str += "</li>";
                    }
                })};
                str += "</ul>";
                if (matchcounts == 0) { str = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>' }
                if (keywords == "") { str = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>' }
                $resultContent.innerHTML = str;
            });
            proceedsearch();
        }
    });}

    // handle and trigger popup window;
    $('.popup-trigger').mousedown(function(e) {
      e.stopPropagation();
      if (isfetched == false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };

    });

    $('.popup-btn-close').click(function(e){
      $('.popup').hide();
      $(".popoverlay").remove();
      $('body').css('overflow', '');
    });
    $('.popup').click(function(e){
      e.stopPropagation();
    });
  </script>

  

  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.1.js"></script>
  <script>AV.initialize("Qv6ckEtL1pe3PJD10qoOLKtg-gzGzoHsz", "NXiHFodQfmI8oxkK6IThhjrF");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  
<script type="text/javascript" src="/js/src/particle.js" count="50" zindex="-2" opacity="1" color="0,104,183"></script>
</body>
</html>
